class PresenceObserver < ActiveRecord::Observer
  def after_create(presence)

    # Continued from Command.rb
    
    buddies = get_online_buddies(presence)
    
    unless buddies.empty?
      # 3) Report to user which buddies of her are here
      report_buddies_to_user(presence, buddies)
      # 4) Report to other buddies present user is here
      report_to_buddies_user_is_here(presence, buddies) 
    end
    
    # Acknowledge presence is established
    report_reception_ok(presence)
    
  end
  
  def get_online_buddies(presence)

    Presence.find_by_sql(['SELECT i.login, i.service, u.email, u.phone FROM presences AS p INNER JOIN connections AS c ON (left_side_user = ? OR right_side_user = ?) INNER JOIN identities AS i ON (i.user_id = p.user_id) INNER JOIN users AS u ON (i.user_id = u.id) WHERE identifier = ? AND p.user_id <> ? GROUP BY (u.email) ORDER BY p.id DESC', presence.user_id, presence.user_id, presence.identifier, presence.user_id])

  end
  
  def report_reception_ok(presence)
    Notifier.deliver_report_reception_ok(presence)
  end
  
  def report_buddies_to_user(presence, buddies)
    Notifier.deliver_report_buddies_to_user(presence, buddies)
  end
  
  def report_to_buddies_user_is_here(presence, buddies) 
    buddies.each do |buddy| 
      Notifier.deliver_report_to_buddies_user_is_here(presence, buddy)
    end
  end

end
